from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from .models import Student, Student_last, Rating
from django.urls import reverse
from .forms import EditorForm, CommentForm
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

# Create your views here.

def index(request):
	all_student = Student.objects.all().order_by('seat_number')
	student_true = []
	student_false = []
	for student in all_student:
		if student.bool_intro:
			student_true.append(student)
		else:
			student_false.append(student)

	context = {"student_true":student_true, "student_false":student_false}
	return render(request, 'student/index.html', context=context)

@login_required
def look(request, seat_number):
	# 查询学生
	look_student = get_object_or_404(Student, seat_number=seat_number)
	context = {"look_student" : look_student}
	look_student.html_text = look_student.student_intro.html
	look_student.save()
	context['html'] = look_student.student_intro.html
	# 统计得分
	rating = Rating.objects.filter(be_graded=look_student)
	lens = Rating.objects.filter(be_graded=look_student).count()
	score = {'iq':0, 'eq':0, 'relation':0}
	for rate in rating:
		score['iq'] += rate.iq
		score['eq'] += rate.eq
		score['relation'] += rate.relation
	if lens != 0:
		score['iq'] = round(score['iq']/lens,1)
		score['eq'] = round(score['eq']/lens,1)
		score['relation'] = round(score['relation']/lens,1)
	context['score'] = score
	# 渲染页面
	return render(request, 'student/student.html', context=context)

@login_required
def editor(request, seat_number):
	if request.method == 'POST':
		look_student = get_object_or_404(Student, seat_number=seat_number)
		last_student = Student_last()
		if request.POST["intro"] == None or request.POST['qq'] == None or request.POST['phone'] == None:
			return render(request, "student/error.html", {'error_message':"同学录的内容不能为空！"})

		if look_student.bool_intro == True:
			last_student.student_info = look_student.student_intro
			last_student.qq_number = look_student.qq_number
			last_student.phone_number = look_student.phone_number
			last_student.last_edit = look_student.last_edit
			last_student.last_edit_name = look_student.last_edit_name
			last_student.history = look_student
			last_student.save()

		look_student.student_intro = request.POST["intro"]
		look_student.qq_number = request.POST["qq"]
		look_student.phone_number = request.POST['phone']
		look_student.last_edit_name = request.user.username
		look_student.bool_intro = True
		look_student.save()
	
		return HttpResponseRedirect(reverse("student:look", kwargs={"seat_number":seat_number}))
	else:
		look_student = get_object_or_404(Student, seat_number=seat_number)
		if request.user != look_student.user:
			return render(request, "student/error.html", {'error_message':'非本人不能编辑别人的同学录哦！'})
		editor_form = EditorForm()
		editor_form.fields['intro'].initial = look_student.student_intro
		editor_form.fields['qq'].initial = look_student.qq_number
		editor_form.fields['phone'].initial = look_student.phone_number
		context = {"look_student":look_student, 'editor_form':editor_form}
		return render(request, "student/editor.html", context=context)

def history(request, seat_number):
	look_student = get_object_or_404(Student, seat_number=seat_number)
	all_history = look_student.history.all().order_by('-last_edit')
	context = {'look_student':look_student, 'history':all_history}
	return render(request, "student/history.html", context=context)

def history_spe(request, seat_number, serial_number):
	historys = get_object_or_404(Student_last, id=serial_number)
	# render_md = mistune.create_markdown(plugins=['strikethrough', 'table'])
	# markdown_html = render_md(historys.student_info)
	historys.html_text = historys.student_info.html
	historys.save()
	context = {'history': historys, 'seat_number': seat_number, 'name': get_object_or_404(Student, seat_number=seat_number).name}
	return render(request, 'student/history_spe.html', context=context)

# 2025/07/07 评论模块
@login_required
def comment_editor(request, seat_number):
	look_student = get_object_or_404(Student, seat_number=seat_number)
	comment = Rating.objects.filter(grader=request.user, be_graded=look_student)
	comment_form = CommentForm()
	try:
		comment_form.fields['iq'].initial = comment[0].iq
		comment_form.fields['eq'].initial = comment[0].eq
		comment_form.fields['relation'].initial = comment[0].relation
		comment_form.fields['comment'].initial = comment[0].comment
		comment_form.fields['is_pravite'].initial = comment[0].is_private
	except:
		pass
	if request.method == 'POST':
		look_student = get_object_or_404(Student, seat_number=seat_number)
		try:
			comment = Rating.objects.filter(grader=request.user, be_graded=look_student).first()
		except:
			comment = Rating()
		if comment == None:
			comment = Rating()
		if request.POST["comment"] == None:
			return render(request, "student/comment_editor.html", 
				 {'comment_form':comment_form, 'look_student':look_student, 'error_message':"貌似有一些内容为空"})

		comment.iq = request.POST['iq']
		comment.eq = request.POST['eq']
		comment.relation = request.POST['relation']
		comment.comment = request.POST['comment']
		comment.is_private = (request.POST.get('is_private') == 'on')
		comment.grader = request.user
		comment.be_graded = get_object_or_404(Student, seat_number=seat_number)
		comment.save()
	
		return HttpResponseRedirect(reverse("student:look", kwargs={"seat_number":seat_number}))
	else:
		context = {'comment_form':comment_form, 'look_student':look_student}
		return render(request, "student/comment_editor.html", context=context)

@login_required
def comment_total(request, seat_number, page_number):
	look_student = get_object_or_404(Student, seat_number=seat_number)
	if look_student.user == request.user:
		comments = list(Rating.objects.filter(be_graded=look_student))
	else:
		comments = list(Rating.objects.filter(be_graded=look_student, is_private=False))
		pri_comment = Rating.objects.filter(be_graded=look_student, is_private=True, grader=request.user).first()
		if pri_comment != None:
			comments.append(pri_comment)
			print(pri_comment.is_private)
	
	page_com = Paginator(comments, 10)
	try:
		com_now = page_com.page(page_number)
	except PageNotAnInteger:
		return HttpResponseRedirect(reverse("student:comment_total", 
									  kwargs={"seat_number":seat_number, "page_number":1}))
	except EmptyPage:
		return HttpResponseRedirect(reverse("student:comment_total", 
									  kwargs={"seat_number":seat_number, 'page_number':page_com.num_pages}))
	
	context =  {'comment_now':com_now, 'look_student':look_student}
	context['pre'] = com_now.has_previous()
	context['next'] = com_now.has_next()
	context['total'] = page_com.num_pages
	context['now'] = page_number
	context['num_pre'] = page_number-1
	context['num_next'] = page_number+1
	return render(request, 'student/comment_total.html', context=context)

@login_required
def comment(request, seat_number):
	return HttpResponseRedirect(reverse("student:comment_total", kwargs={"seat_number":seat_number, "page_number":1}))